package com.nce.web;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.nce.entity.Msg;
import com.nce.entity.Vp;
import com.nce.service.ServiceException;
import com.nce.service.VpService;

/**
 * 用户管理Action.
 * 
 * 使用Struts2 convention-plugin annotation定义Action参数.
 * 演示带分页的管理界面.
 * 
 * @author GT
 */
//定义URL映射对应/account/user.action
@Namespace("/admin")
//定义名为reload的result重定向到user.action, 其他result则按照convention默认.
@Results( { @Result(name = CrudActionSupport.RELOAD, location = "vp.action", type = "redirect"), @Result(name = "home", location = "/", type = "redirect") })
public class VpAction extends CrudActionSupport<Vp> {

	private static final long serialVersionUID = 8683878162525847072L;

	@Autowired
	private VpService vpService;

	//-- 页面属性 --//
	private Long id;
	private Vp entity = new Vp();
	private Page<Vp> page = new Page<Vp>(20);//每页5条记录
	
	private String path;
	

	//-- ModelDriven 与 Preparable函数 --//
	public void setId(Long id) {
		this.id = id;
	}

	public Vp getModel() {
		return entity;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = vpService.getVp(id);
		} else {
			entity = new Vp();
		}
	}
	
	public String importVp() throws Exception {
		String filepath = Struts2Utils.getParameter("path");		
		
		if(filepath==null){
			addActionMessage("文件路径错误:"+filepath);
		}
		
		
		try {
			List<Vp> vpList = parseVp(path);
			int total = vpList.size();
			vpService.saveVpList(vpList);
			
			addActionMessage( "数据成功导入共: "+total+"条");
			logger.warn("数据成功导入共: "+total+"条,文件:"+filepath);
		} catch (Exception e) {			
			addActionMessage( "导入数据出错,文件路径为:["+filepath+"],更多消息:"+e.getMessage());
			logger.error("导入数据出错,文件路径为:["+filepath+"]",e);
		}		
		
		return list();

	}

	//-- CRUD Action 函数 --//
	@Override
	public String list() throws Exception {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		//设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy("id");
			page.setOrder(Page.ASC);
		}
		page = vpService.findVp(page, filters);
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		return INPUT;
	}

	@Override
	public String save() {
		if(entity.getId()==null){
			entity.setCtime(new Date());
		}
		vpService.saveVp(entity);
		addActionMessage("保存人员成功");
		return RELOAD;
		
	}
		
	
	public void prepareReg() throws Exception {
		prepareModel();
	}

	@Override
	public String delete() throws Exception {
		vpService.deleteVp(id);
		addActionMessage("删除人员成功");
		return RELOAD;
	}

	public String deleteAll() throws Exception {
		vpService.deleteAllVP();
		addActionMessage("删除所有人员成功");
		return RELOAD;
	}


	

	public VpService getVpService() {
		return vpService;
	}

	public void setVpService(VpService vpService) {
		this.vpService = vpService;
	}

	public void setPage(Page<Vp> page) {
		this.page = page;
	}
	
	

	public Page<Vp> getPage() {
		return page;
	}

	public Vp getEntity() {
		return entity;
	}

	public void setEntity(Vp entity) {
		this.entity = entity;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}
	
	private List<Vp> parseVp(String path) {
		List<Vp> vpList = new ArrayList<Vp>();
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(new FileInputStream(path), "GBK");

			BufferedReader br = new BufferedReader(isr);
			String lineStr = "";
			int lineNumber = 0;
			while ((lineStr = br.readLine()) != null) {
				String [] vpArr = lineStr.split(",");
				if(vpArr!=null ){
					Vp vp = new Vp();
					if (vpArr.length > 0) {
						vp.setQqid(vpArr[0]);
					}
					if (vpArr.length > 1) {
						vp.setUsername(vpArr[1]);
					}
					if (vpArr.length > 2) {
						vp.setPhone(vpArr[2]);
					}
					if (vpArr.length > 3) {
						vp.setEmail(vpArr[3]);
					}
					if (vpArr.length > 4) {
						vp.setAddress(vpArr[4]);
					}
					if (vpArr.length > 5) {
						vp.setMemo(vpArr[5]);
					}
					vpList.add(vp);
					System.out.println(vp);
				}else{
					
				}
			}
		} catch (Exception e) {
			throw new ServiceException("解析监控人员名单出错."+e.getMessage(),e);
		} finally {
			try {
				if(isr!=null){
					isr.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return vpList;
	}
	
	/**
	 * 导出所有监控人员
	 * @return
	 */
	public String export(){
		//内容并操作
		//内容并操作
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());	
	
		
		List<Vp> vpList = vpService.findVpList(filters)	;
		if(vpList!=null && vpList.size() > 0){
			String abc = Struts2Utils.getRequest().getRealPath("/down/");
			Format formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
		    String dateStr = formatter.format(new Date());
		    String downUrl = "http://127.0.0.1/down/"+dateStr+"_vp.dam";
		    	BufferedWriter out = null;
				try {
			        out = new BufferedWriter(new FileWriter(abc+"/"+dateStr+"_vp.dam"));

			        for(Vp vp : vpList){			        	
			        	out.write(vp.formatToTxt());			        	
			        	out.flush();
			        }		        
			        
			    } catch (IOException e) {
			    	logger.error("导出监控人员文件出错",e);
			    }finally{
			    	if(out!=null){
			    		try {
							out.close();
						} catch (IOException e) {
							logger.error("导出监控人员文件出错",e);
						}
			    	}
			    }
			    
			    try {
					Struts2Utils.getResponse().sendRedirect(downUrl);
				} catch (IOException e) {					
					logger.error("导出监控人员文件出错",e);
				}    
		}	
		return null;
	}
	
}
